package org.easy.core.util;


import org.easy.core.dto.ExceptionModel;
import org.easy.core.exception.BizRuntimeException;

import java.util.ArrayList;
import java.util.List;


public class ThrowableUtil {
    //todo 输入需要展示的包
    private static final String[] LOG_PACKAGES = new String[]{"com.link", "com.baomidou.mybatisplus"};


    public static ExceptionModel encoder(BizRuntimeException bizRuntimeException) {
        ExceptionModel model = encoder((Throwable) bizRuntimeException);
        model.setMsg(bizRuntimeException.getMsg());
        model.setCode(bizRuntimeException.getCode());
        return model;
    }

    public static ExceptionModel encoder(Throwable throwable) {
        ExceptionModel model = new ExceptionModel();
        model.setCode(500);
        model.setMsg(throwable.getMessage());

        model.setStacks(getStacks(throwable));
        return model;
    }


    private static List<String> getStacks(Throwable businessRuntimeException) {
        List<String> simpleStack = new ArrayList<>();
        simpleStack.add(businessRuntimeException.toString());

        for (StackTraceElement stackTraceElement : businessRuntimeException.getStackTrace()) {
            for (String logPackage : LOG_PACKAGES) {
                if (stackTraceElement.getClassName().startsWith(logPackage)) {
                    simpleStack.add("\tat " + stackTraceElement);
                }
            }

        }
        return simpleStack;
    }


}
